var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')

var indexRouter = require('./routes/index')
var usersRouter = require('./routes/users')
const blogRouter = require('./routes/blog')
const userRouter = require('./routes/user')

var app = express()

// view engine setup
// node.js的动态Html渲染，类似java的jsp页面 和c#的asp页面(一般只做后端应用，不做前端页面)
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'jade')

// 日志记录中间件 📝
app.use(logger('dev'))
// 解析请求体中间件
app.use(express.json()) // 解析post json参数
app.use(express.urlencoded({ extended: false })) // 解析post x-www-form-urlencoded参数
// 解析cookie中间件
app.use(cookieParser())
// 静态文件中间件
app.use(express.static(path.join(__dirname, 'public')))

// 路由中间件
app.use('/', indexRouter)
app.use('/users', usersRouter)
app.use('/api/blog', blogRouter) // api/blog/xxx 父路由 + 子路由
app.use('/api/user', userRouter)

// catch 404 and forward to error handler
// 404中间件，当找不到路由时，会执行这个中间件
app.use(function (req, res, next) {
  next(createError(404))
})

// error handler
// 错误处理中间件
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  // render the error page
  res.status(err.status || 500)
  res.render('error')
})

module.exports = app
